package main

import (
	"context"
	"fmt"
	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/sd"
	"github.com/go-kit/kit/sd/consul"
	"github.com/go-kit/kit/sd/lb"
	"github.com/go-kit/kit/transport/http"
	"github.com/hashicorp/consul/api"
	"go-kit/demo12/Endpoint"
	"go-kit/demo12/Transpoint"
	"io"
	"net/url"
	"os"
	"time"
)

//挂起一个HTTP 服务 并把请求 传递给service 层
func main() {

	//获取配置对象
	config := api.DefaultConfig()

	//设置地址
	config.Address = "localhost:8500"

	apiClient, _ := api.NewClient(config)

	client := consul.NewClient(apiClient)

	var logger log.Logger
	{
		logger = log.NewLogfmtLogger(os.Stdout)

		var Tag = []string{"caiji"}

		//最后的true表示只有通过健康检查的服务才能被得到
		instancer := consul.NewInstancer(client, logger, "菜鸡飞", Tag, true)
		{
			factory := func(serviceUrl string) (endpoint.Endpoint, io.Closer, error) {

				//server ip + 8080 真是服务器的地址
				tart, _ := url.Parse("http://" + serviceUrl)

				return http.NewClient("GET", tart, Transpoint.GetUserInfoRequest, Transpoint.GetUserInfoResponse).Endpoint(), nil, nil

			}

			endpointer := sd.NewEndpointer(instancer, factory, logger)

			endpoints, _ := endpointer.Endpoints()

			fmt.Println("服务有", len(endpoints), "条")

			//使用go-kit自带的轮询
			mylb := lb.NewRandom(endpointer, time.Now().UnixNano())

			for {

				//写死获取第一个
				getUserInfo, err := mylb.Endpoint()

				//创建一个 context 上下文
				ctx := context.Background()

				//执行
				res, err := getUserInfo(ctx, Endpoint.UserRequest{Uid: 101})

				if err != nil {

					fmt.Println(err)

					os.Exit(1)
				}

				//断言，得到响应值
				userinfo := res.(Endpoint.UserResponse)

				fmt.Println(userinfo.Result)

			}

			//写死获取第一条
			GetUserInfo := endpoints[0]

			//创建一个 context 上下文对象
			ctx := context.Background()

			//执行
			res, err := GetUserInfo(ctx, Endpoint.UserRequest{Uid: 300})

			if err != nil {

				fmt.Println(err)

				os.Exit(1)

			}

			//断言 得到响应值
			userinfo := res.(Endpoint.UserResponse)

			fmt.Println(userinfo.Result)

		}

	}

}
